﻿using System;
using MediatR;
using System.Collections.Generic;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.MWeb;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.Extensions.Options;
using Casamiel.Common;
using Newtonsoft.Json;
using System.Linq;

using Casamiel.Domain.Request;
using Newtonsoft.Json.Linq;
using Casamiel.Domain.Request.IC;
using System.Globalization;
using Casamiel.Common.Extensions;

namespace Casamiel.Application.Commands
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class BuyNowCommandHandler : BaseCommandHandler, IRequestHandler<BuyNowCommand, BaseResult<BuyNowRsp>>
    {

        private readonly IMbrStoreRepository _mbrStoreRepository;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="netICService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="settings"></param>
        public BuyNowCommandHandler(IMbrStoreRepository mbrStoreRepository, INetICService netICService,
            IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
        {
            _mbrStoreRepository = mbrStoreRepository;

        }

        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<BaseResult<BuyNowRsp>> Handle(BuyNowCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var storeinfo = await _mbrStoreRepository.GetKeyAsync<ICasaMielSession>(request.Storeid).ConfigureAwait(false);
            if (storeinfo == null)
            {
                return new BaseResult<BuyNowRsp>(null, 9999, "门店信息有误！");
            }
            if (storeinfo.IsCakeClose == 1)
            {
                return new BaseResult<BuyNowRsp>(null, 9999, "抱歉门店已闭店！");
            }
			//if(storeinfo.IsOpenSend==0 && request.OrderType!=1)
			//{
			//    return new BaseResult<BuyNowRsp>(null, 9999, " 不支持送货上门！");
			//}
			if(request.TakeTime.Month == 1){
				if (request.TakeTime.Year == 2019) {
					request.TakeTime=request.TakeTime.AddYears(1);
				}
			 
			}
            if (request.TakeTime < DateTime.Now)
            {
                return new BaseResult<BuyNowRsp>(null, -25, "提货时间有误！");
            }

            var goodsbase = await this.GetGoodsByIdStoreId(request.Storeid, request.GoodsBaseId).ConfigureAwait(false);
            OrderLogger.Trace($"{JsonConvert.SerializeObject(goodsbase)}");
            if (goodsbase == null || goodsbase.Status == 0)
            {
                return new BaseResult<BuyNowRsp>(null, -22, "产品已经下架！");
            }
            var icpricereq = new IcPriceReq
            {
                Shopid = storeinfo.RelationId,
                Product = new List<ProductItemReq>(),
                Datasource=$"{request.DataSource}099".ToInt32(0)
            };
            icpricereq.Product.Add(new ProductItemReq { Pid = $"{goodsbase.GoodsRelationId}" });
            var icpriceRsp = await NetICService.Icprice(icpricereq).ConfigureAwait(false);
            if (icpriceRsp.product != null && icpriceRsp.product.Count > 0)
            {
                goodsbase.CostPrice = icpriceRsp.product[0].icprice;
            }
            var buyNowRsp = new BuyNowRsp
            {
                Price = goodsbase.Price,
                ProductBaseId = goodsbase.ProductBaseId,
                ImageUrl = goodsbase.ImageUrl,
                Quantity = request.Count,
                GoodsId = request.GoodsBaseId,
                GoodsRelationId = request.GoodsRelationId,
                CostPrice = goodsbase.CostPrice,
                Status = goodsbase.Status,
                StockDays = goodsbase.StockDays,
                StoreId = request.Storeid,
                StoreName = storeinfo.StoreName,
                TakeTime = request.TakeTime,
                Title = goodsbase.Title,
                StoreRelationId = storeinfo.RelationId,
                GoodsProperty = goodsbase.GoodsProperty
            };
            var stockreq = new ProductStockQueryReq { shopid = storeinfo.RelationId, product = new List<ProductStockReq>() };
            stockreq.product.Add(new ProductStockReq
            {
                pid = $"{buyNowRsp.GoodsRelationId}",
                count = buyNowRsp.Quantity
            });
            if(this.Casasettings.ApiName== "doncoApi") {
				//if (storeinfo.IsLimitStock == 0) {
					if (goodsbase.StockDays > 1) {
						if (request.TakeTime.DayOfYear != DateTime.Now.DayOfYear) {
							if (request.TakeTime.DayOfYear < DateTime.Now.AddDays(goodsbase.StockDays).DayOfYear) {
								return new BaseResult<BuyNowRsp>(null, -28, "本款蛋糕需提前2天预定" );
							}
						}
					}
				//}


				if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:00:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) < DateTime.Parse(request.TakeTime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
					return new BaseResult<BuyNowRsp>(null, -23, "抱歉该自提时间不能预定" );
				}
				//if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00")) && data.picktime.DayOfYear == DateTime.Now.AddDays(1).DayOfYear)
				//{
				//    return Ok(new { code = -23, msg = "抱歉该时间段不能预定次日蛋糕" });
				//}
				if (request.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
					if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) && request.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
						return new BaseResult<BuyNowRsp>(null, -23, "抱歉该时间段不能预定当天蛋糕自提" );
					}

				}
			}
			else
            {
				if (request.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
					if (storeinfo.IsLimitStock == 0) {

						var zmodel = await NetICService.Productstockquery(stockreq).ConfigureAwait(false);
						if (zmodel != null && zmodel.product.Count > 0) {

							if (zmodel.product[0].count < request.Count) {
								return new BaseResult<BuyNowRsp>(null, -21, "库存不足");
							}
						} else {
							return new BaseResult<BuyNowRsp>(null, -21, "库存不足");
						}

					}
				}
				if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US")) < DateTime.Parse(request.TakeTime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US")))
                {
                    return new BaseResult<BuyNowRsp>(null, -23, "抱歉该自提时间不能预定");
                }

                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture))
                {
                    if (request.TakeTime < DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyyy-MM-dd 23:00:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture))
                    {
                        var zmodel = await NetICService.Productstockquery(stockreq).ConfigureAwait(false);
                        if (zmodel != null && zmodel.product.Count > 0)
                        {
                            // int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(data.relationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")));

                            if (zmodel.product[0].count < request.Count)
                            {
                                return new BaseResult<BuyNowRsp>(null, -21, "库存不足");
                            }
                        }
                        else
                        {
                            return new BaseResult<BuyNowRsp>(null, -21, "库存不足");
                            //logger.Error($"buynowerror:{JsonConvert.SerializeObject(dto)},{JsonConvert.SerializeObject(zmodel)}");
                            //return Ok(new { code = -22, msg = "产品已经下架" });
                        }
                        return new BaseResult<BuyNowRsp>(buyNowRsp, 0, "可以购买");
                    }
                    return new BaseResult<BuyNowRsp>(buyNowRsp, 0, "可以购买");
                }
            }

            

            return new BaseResult<BuyNowRsp>(buyNowRsp, 0, "可以购买");
        }
    }
}
